package com.xindz.hgq.utils.greendao;

import android.content.Context;

import com.xindz.hgq.database.greendao.bean.DaoMaster;
import com.xindz.hgq.database.greendao.bean.DaoSession;

import org.greenrobot.greendao.database.Database;

import java.lang.ref.WeakReference;

/**
 * @name GreenDao
 * @class name：com.xindz.greendaoone.app
 * @describe describe
 * @anthor XINDZ
 * @time 2018/5/14 11:31
 * @change
 * @chang time
 * @class describe
 */
public class DbManager {
    /**
     * 是否加密
     */
    public static final boolean ENCRYPTED = false;
    /**
     * 数据库名称
     */
    private static final String DB_NAME = "lztx.db";
    /**
     * 加密数据库名称
     */
    private static final String DB_NAME_ENCRYPTED = "lztx-encrypted.db";
    private static final String ENCRYPTED_KEY = "qwe-asd";

    private static volatile DbManager mDbManager;
    private static DaoMaster mDaoMaster;
    private static DaoSession mDaoSession;
    private final WeakReference<Context> mContext;
    private DaoMaster.DevOpenHelper mDevOpenHelper;

    private DbManager(Context context) {
        mContext = new WeakReference<>(context);
        mDevOpenHelper = new DaoMaster.DevOpenHelper(mContext.get(), ENCRYPTED ? DB_NAME_ENCRYPTED : DB_NAME);
        mDaoMaster = getDaoMaster();
        mDaoSession = getDaoSession();

    }

    /**
     * 获取DaoMaster
     * <p>
     * 判断是否存在数据库，如果没有则创建数据库
     *
     * @return
     */
    public DaoMaster getDaoMaster() {
        if (null == mDaoMaster) {
            synchronized (DbManager.class) {
                if (null == mDaoMaster) {
                    MyOpenHelper helper = new MyOpenHelper(mContext.get(), ENCRYPTED ? DB_NAME_ENCRYPTED : DB_NAME, null);
                    Database db = ENCRYPTED ? helper.getEncryptedWritableDb(ENCRYPTED_KEY) : helper.getWritableDb();
                    mDaoMaster = new DaoMaster(db);
                }
            }
        }
        return mDaoMaster;
    }

    /**
     * 获取DaoSession
     *
     * @return
     */
    public DaoSession getDaoSession() {
        if (null == mDaoSession) {
            synchronized (DbManager.class) {
                mDaoSession = getDaoMaster().newSession();
            }
        }

        return mDaoSession;
    }

    public static DbManager getInstance(Context context) {
        if (null == mDbManager) {
            synchronized (DbManager.class) {
                if (null == mDbManager) {
                    mDbManager = new DbManager(context);
                }
            }
        }
        return mDbManager;
    }

    /**
     * 获取可读数据库
     *
     * @return
     */
    public Database getReadableDatabase() {
        return ENCRYPTED ? mDevOpenHelper.getEncryptedReadableDb(ENCRYPTED_KEY) : mDevOpenHelper.getReadableDb();
    }

    /**
     * 获取可写数据库
     *
     * @return
     */
    public Database getWritableDatabase() {
        return ENCRYPTED ? mDevOpenHelper.getEncryptedWritableDb(ENCRYPTED_KEY) : mDevOpenHelper.getWritableDb();
    }


}
